package com.example.shushiyunsst.fragment.main.transaction.child.content

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.transaction.bean.ContentListBean
import com.example.shushiyunsst.fragment.main.transaction.bean.TransIndexDelegateBean
import com.example.shushiyunsst.fragment.main.transaction.bean.TransactionUIInvokeListener
import com.example.shushiyunsst.fragment.main.transaction.child.TRANSFER_DECIMAL_FORMAT
import com.example.shushiyunsst.fragment.main.transaction.child.transfer_index
import com.example.shushiyunsst.fragment.main.transaction.child.transfer_index_data
import com.example.shushiyunsst.fragment.main.transaction.child.transfer_index_data_failed
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type
import java.text.DecimalFormat

class TransactionContentListFragment : SimpleListFragment<TransIndexDelegateBean>(),
    OnItemChildClickListener {


    companion object {
        fun newInstance(): TransactionContentListFragment {
            val args = Bundle()
            val fragment = TransactionContentListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val df = DecimalFormat(TRANSFER_DECIMAL_FORMAT)

    private val sstStr = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private var transactionUIInvokeListener: TransactionUIInvokeListener? = null

    fun setTransactionUIInvokeListener(listener: TransactionUIInvokeListener?): TransactionContentListFragment {
        this.transactionUIInvokeListener = listener
        return this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        isEnableLoadMore = false
        isAddDividerItemDecoration = false
        isInitialRefresh = false
    }


    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundColor(Color.TRANSPARENT)
        mSwipeRefreshLayout.setColorScheme(R.color.nav_bar_bg_color)
        mRecyclerView.overScrollMode = View.OVER_SCROLL_NEVER
        mSwipeRefreshLayout.setProgressBackgroundColor(R.color.colorAccent)

        list_empty_view.removeAllViews()
        addEmptyView(R.layout.transaction_content_list_empty)

        mAdapter.addChildClickViewIds(R.id.cancel_deal)
        mAdapter.setOnItemChildClickListener(this)

        mSwipeRefreshLayout.isEnabled = false
    }

    override fun getItemLayout() = R.layout.transaction_content_list_fragment

    override fun convertItem(helper: JssBaseViewHolder?, item: TransIndexDelegateBean?) {
        val transactionTypeStr = if (item?.txType == 1) "买" else "卖"
        val transactionTypeColor =
            if (item?.txType == 1) R.color.PrimaryColor else R.color.image_color_red
//        val statusDesc = if (item?.txStatus == 1) "交易中" else "交易完成"
        val statusDesc =
            when (item?.txStatus) {
                0 -> "已撤销"
                2 -> "完成"
                1 -> "进行中"
                else -> ""
            }
//        item?.tokenType=AppGlobals.getApplication().getString(R.string.wallet_sst)

        helper?.setText(R.id.transactionTypeTv, transactionTypeStr)
            ?.setViewVisible(R.id.cancel_deal, item?.txStatus == 1)

            ?.setText(R.id.statusDesc, statusDesc)
            ?.setTextColorRes(R.id.transactionTypeTv, transactionTypeColor)
            ?.setText(R.id.transactionTimeTv, "${item?.createTime}")
            ?.setText(R.id.transactionPriceTitleTv, "价格（${sstStr})")
            ?.setText(R.id.transactionCountTitleTv, "数量（${item?.tokenType})")
            ?.setText(R.id.actuallyDealTitleTv, "实际成交（${item?.tokenType})")
            ?.setText(R.id.transactionPriceTv, df.format(item?.txPrice))
            ?.setText(R.id.transactionCountTv, df.format(item?.txNums))
            ?.setText(R.id.actuallyDealTv, df.format(item?.txNumsDeal))

    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(ContentListBean::class.java).endSubType().build()
    }


    override fun handMessage(msg: MessageWrap?) {

        when (msg?.message) {
            transfer_index -> {

                onRefresh()
            }
            transfer_index_data -> {
                val list = transactionUIInvokeListener?.getTransIndexNode()?.bean?.list

                mAdapter.clears()
                loadListDate(list)
            }
            transfer_index_data_failed -> {

                onFailed()
            }
        }

    }

    override fun onRefresh() {

        pageIndex = 1
        mAdapter.isUseEmpty = false

        mAdapter.notifyDataSetChanged()
        mAdapter.clears()
        val iconType = transactionUIInvokeListener?.getTransIndexNode()?.iconType

        if (iconType != null) {
            mSwipeRefreshLayout.postDelayed({ netRequest() }, delayedTime.toLong())
        }

    }


    override fun netRequest() {

        transactionUIInvokeListener?.requestIndex()
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.cancel_deal -> {
                cancelDeal(item)
            }
        }
    }

    private fun cancelDeal(item: TransIndexDelegateBean?) {

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo


        val map = mapOf(
            "txId" to "${item?.txId}",
            "uid" to "${userInfo?.uid}"
        )

        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.cancelTransTxList)
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_LONG).show()
                transactionUIInvokeListener?.requestIndex()
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }
}